﻿var serviceId = GetQueryString("Id");
var sourceId = GetQueryString("dataSourceId");
var ServiceTypelist = GetDataServiceTypeList();
var edit;
$(function () {
    $('#ctlListTaskCategory').on('change', function(){
        listSubTaskCategory();
    });
    listTaskCategory();
    //执行初始化
    getServiceDetails();
    getDataSourceDetails();
    //类型的改变
    $(".TaskType").change(function () {
        var id = $(this).attr("data-type");
        $(".taskoption").hide();
        if (id != "") {
            $("#" + id).show();
        }
        $("#RunModeId").val($(this).val());
        $(".typeOption").removeClass("required");
        $("." + id + "Option").addClass("required");
    });

    //新增闹钟模式中类型的修改
    $("#add-alarmclock-type").change(function () {
        $("#add-alarmclock-value").val("");
        var $thisval = parseInt($(this).val());
        if ($thisval == 3) {
            $("#insert-week").show();
            $("#insert-other").hide();
        } else {
            $("#insert-other").show();
            $("#insert-week").hide();
        }
    });
    //修改闹钟模式中类型的修改
    $("#update-alarmclock-type").change(function () {
        $("#update-alarmclock-value").val("");
        var $thisval = parseInt($(this).val());
        if ($thisval == 3) {
            $("#update-week").show();
            $("#update-other").hide();
        } else {
            $("#update-other").show();
            $("#update-week").hide();
        }
    });
    $("#add-alarmclock-value").click(function () {
        var id = parseInt($("#add-alarmclock-type").val());
        switch (id) {
            case 1:
                WdatePicker(({ dateFmt: 'MM-dd HH:mm:ss' }));
                break;
            case 2:
                WdatePicker(({ dateFmt: 'dd HH:mm:ss'}));
                break;
            case 3:
                //WdatePicker(({ isShowWeek: true, onpicked: funccc, errDealMode: 3 }));
                break;
            case 4:
                WdatePicker(({ dateFmt: 'HH:mm:ss' }));
                break;
        }
    });
    /*$("#add-alarmclock-value").blur(function () {
        var id = parseInt($("#add-alarmclock-type").val());
        if (id == 3) {
            var reg = new RegExp("^[1-7]{1}$");
            if (!reg.test($("#add-alarmclock-value").val())) {
                ShowGritter("请输入数字1到7");
                $("#add-alarmclock-value").val("");
            }
        }
    });*/
    $("#update-alarmclock-value").click(function () {
        var id = parseInt($("#update-alarmclock-type").val());
        switch (id) {
            case 1:
                WdatePicker(({ dateFmt: 'MM-dd HH:mm:ss' }));
                break;
            case 2:
                WdatePicker(({ dateFmt: 'dd HH:mm:ss', minDate: '%y-01-01', maxDate: '%y-01-31' }));
                break;
            case 3:
                break;
            case 4:
                WdatePicker(({ dateFmt: 'HH:mm:ss' }));
                break;
        }
    });
    /*$("#update-alarmclock-value").blur(function () {
        var id = parseInt($("#update-alarmclock-type").val());
       
    });*/
    $("#update-alarmclock-form").validate({
        submitHandler: function (form) {
            var jsonobj = { type: $("#update-alarmclock-type").val(), value: $("#update-alarmclock-value").val() };
            var tempweek = "";
            if (jsonobj.type == "3") {
                jsonobj.value = { week: $("#update-alarmclock-value-week").val(), weekText: $("#update-alarmclock-value-week").find("option:selected").text(), time: $("#update-alarmclock-value-time").val() };
                tempweek = ("<td>" + jsonobj.value.weekText + " " + jsonobj.value.time + "</td>");
            } else {
                tempweek = ("<td>" + jsonobj.value + "</td>");
            }
            var tr = ("<tr data='" + JSON.stringify(jsonobj) + "'><td>");
            tr += ($("#update-alarmclock-type").find("option:selected").text() + "</td>");
            tr += tempweek;
            tr += ("<td><a href='javascript:void(0);' onclick='DeleteData(this)' >删除</a><a href='javascript:void(0);' onclick='updatealarmclock(this)' >修改</a> </td>");
            $(tr).replaceAll(edit);
            $("#update-alarmclock-modal").modal("hide");

        }
    });
    $("#add-alarmclock-form").validate({
        submitHandler: function (form) {
            var jsonobj = { type: $("#add-alarmclock-type").val(), value: $("#add-alarmclock-value").val() };
            var tempweek = "";
            if (jsonobj.type == "3") {
                jsonobj.value = { week: $("#add-alarmclock-value-week").val(), weekText: $("#add-alarmclock-value-week").find("option:selected").text(), time: $("#add-alarmclock-value-time").val() };
                tempweek = ("<td>" + jsonobj.value.weekText + " " + jsonobj.value.time + "</td>");
            } else {
                tempweek = ("<td>" + jsonobj.value + "</td>");
            }
            var tr = ("<tr data='" + JSON.stringify(jsonobj) + "'><td>");
            tr += ($("#add-alarmclock-type").find("option:selected").text() + "</td>");
            tr += tempweek;
            tr += ("<td><a href='javascript:void(0);' onclick='DeleteData(this)' >删除</a><a href='javascript:void(0);' onclick='updatealarmclock(this)' >修改</a> </td>");
            $("#table-alarmclock-details").append(tr);
            $("#add-alarmclock-modal").modal("hide");

        }
    });
    $("#Add-Form").validate({
        submitHandler: function (form) {
            var data = new Date();
            var runModeSettings = "";
            var parameterNames = [];
            var parameterTypes = [];
            var parameterValues = [];
            var columns = $("#table-details tbody tr");
            if (columns.length > 0) {
                for (var i = 0; i < columns.length; i++) {
                    var tempjson = JSON.parse($(columns[i]).attr("data"));
                    parameterNames.push(tempjson.Id);
                    parameterTypes.push($("#dtcol-type-" + tempjson.editNum).val());
                    parameterValues.push($("#dtcol-value-" + tempjson.editNum).val());
                }
            }

            switch ($("#RunModeId").val()) {
                case "1":
                    runModeSettings = ($("#timer-begindata").val() + "," + $("#timer-interval-type").val() + "," + $("#timer-interval-value").val());
                    break;
                case "2":
                    runModeSettings = "";
                    var alarmclocklist = $("#table-alarmclock-details tbody tr");
                    if (alarmclocklist.length == 0) {
                        ShowGritter("请至少添加一项");
                        return false;
                    }
                    for (var j = 0; j < alarmclocklist.length; j++) {
                        var tempJson = JSON.parse($(alarmclocklist[j]).attr("data"));
                        runModeSettings += (tempJson.type + ",");
                        var nowDate = new Date();
                        if (tempJson.type == "1") {
                            runModeSettings += (data.format("yyyy-") + tempJson.value); //添加年
                        }
                        else if (tempJson.type == "2") {
                            runModeSettings += (data.format("yyyy-MM-") + tempJson.value); //添加年月
                        }
                        else if (tempJson.type == "3") {
                            var tempnowdate = new Date();
                            for (var k = 0; k <= 6; k++) {
                                if (k == 0) {
                                    tempnowdate.addDays(-1);
                                }
                                if (tempnowdate.addDays(1).getWeek() == tempJson.value.weekText) {
                                    runModeSettings += (tempnowdate.format("yyyy-MM-dd ") + tempJson.value.time); //添加年月
                                    break;
                                }
                            }
                        } else if (tempJson.type == "4") {
                            runModeSettings += (data.format("yyyy-MM-dd ") + tempJson.value);
                        }
                        if (j != (alarmclocklist.length - 1)) {
                            runModeSettings += ",";
                        }
                    }
                    break;
                case "4":
                    runModeSettings = ($("#event-interval-value").val());
                    break;
            }
            //$("#EnableCodeConversion").val();
            //$("#EnableDataVerification").val();
            //$("#RunModeSettings").val(runModeSettings);
            //$("#DataServiceId").val(serviceId);
            //$("#DataSourceId").val(sourceId);

            /*
            
                                            <input type="hidden" value="ETL" name="sys:sno" />
                                            <input type="hidden" value="CreateTask" name="sys:act" />
                                            <input type="hidden" value="" name="DataServiceId" id="DataServiceId" />
                                            <input type="hidden" value="" name="DataSourceId" id="DataSourceId" />
                                            <input type="hidden" value="" name="EnableCodeConversion" id="EnableCodeConversion" />
                                            <input type="hidden" value="" name="ParameterSettings" id="ParameterSettings" />
                                            <input type="hidden" value="" name="RunModeSettings" id="RunModeSettings" />
                                            <input type="hidden" value="" name="EnableDataVerification" id="EnableDataVerification" />*/


            var postData = {};
            postData.dataServiceId = serviceId;
            postData.DataSourceId = sourceId;
            postData.categoryId = $('#ctlListSubTaskCategory').val();
            if (!postData.categoryId)
            {
                alert('选择所属系统');
                return;
            }
            postData.EnableCodeConversion = $("#EnableCodeConversionOption").is(":checked") ? true : false;
            postData.EnableDataVerification = $("#EnableDataVerificationOption").is(":checked") ? true : false;
            postData.RunModeSettings = runModeSettings;
            postData.parameterNames = parameterNames;
            postData.parameterTypes = parameterTypes;
            postData.parameterValues = parameterValues;
            postData.runMode = $('#RunModeId').val();
            postData.Name = $('input[name=Name]').val();
            postData.CompleteEvent = $('#CompleteEvent').val();
            
            $.ajax({
                url: g_webApiBaseUrl + "create/task",
                data: postData,
                type: "Post",
                dataType: "json",
                success: function (data) {
                    if (data.IsSuccess) {
                        ShowGritter("新增成功", 2, "SchedulingTaskManagement.html");
                    } else {
                        if (IsLogined(data.ErrorCode)) {
                            alert("失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                        }
                    }
                },
                beforeSend: function () {
                    ShowGritter("提交中");
                },
                error: function () {
                    alert("系统异常，请稍后再试");
                }
            });

        }
    });
});

function listTaskCategory() {
    $.ajax({
        url: g_webApiBaseUrl + 'List/RootTaskCategory',
        type: "Get",
        dataType: "json",
        async: false,
        data: {},
        success: function (data) {
            if (data.IsSuccess) {
                if (data.Data != null && data.Data.length != 0) {
                    for (var index = 0; index < data.Data.length; index++) {
                        $('#ctlListTaskCategory').append('<option value="' + data.Data[index].Id + '">' + data.Data[index].Name + '</option>');
                    }
                }
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert("错误代码：" + data.ErrorCode + "，错误信息：" + data.Message);
                }
            }
        },
        error: function () {
            alert("系统异常，请稍后重试");
        }
    });
}

function listSubTaskCategory() {
    var parentId = $('#ctlListTaskCategory').val();
    if (!parentId) {
        $('#ctlListSubTaskCategory option').remove();
        $('#ctlListSubTaskCategory').append('<option value="">选择系统</option>');
        return;
    }
    $('#ctlListSubTaskCategory option').remove();
    $.ajax({
        url: g_webApiBaseUrl + 'List/SubTaskCategory',
        type: "Get",
        dataType: "json",
        async: false,
        data: { 'parentId': parentId },
        success: function (data) {
            if (data.IsSuccess) {
                if (data.Data != null && data.Data.length != 0) {
                    for (var index = 0; index < data.Data.length; index++) {
                        $('#ctlListSubTaskCategory').append('<option value="' + data.Data[index].Id + '">' + data.Data[index].Name + '</option>');
                    }
                }
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert("错误代码：" + data.ErrorCode + "，错误信息：" + data.Message);
                }
            }
        },
        error: function () {
            alert("系统异常，请稍后重试");
        }
    });
}
var updatealarmclock = function (obj) {
    edit = $(obj).parent().parent();
    var jsonobj = JSON.parse(edit.attr("data"));
    $("#update-alarmclock-type").val(jsonobj.type);
    if (jsonobj.type == "3") {
        $("#update-alarmclock-value-week").val();
        $("#update-alarmclock-value-time").val();
        $("#update-week").show();
        $("#update-other").hide();
    } else {
        $("#update-alarmclock-value").val(jsonobj.value);
    }
    $("#update-alarmclock-modal").modal('show');
}
var addalarmclock = function () {
    document.getElementById("add-alarmclock-form").reset();
    $("#insert-week").hide();
    $("#insert-other").show();
    $("#add-alarmclock-modal").modal('show');
}
//获取服务的详细信息
var getServiceDetails = function () {
    $.ajax({
        url: apiUrl,
        data: {
            "sys:sno": "ETL",
            "sys:act": "GetDataService",
            "DataServiceId": serviceId
        },
        dataType: "json",
        success: function (data) {
            if (data.IsSccuess) {
                $("#ServiceName").val(data.Data.Name);
                $("#ServiceType").val(getServiceTypeName(data.Data.TypeId));
                if (data.Data.TypeId == "872bae09-6b32-4dba-a1c9-b24af3d79757") {
                    $(".TaskType").attr("disabled", "disabled");
                }
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert(data.Message);
                }
            }
        },
        beforeSend: function () {
            // $("btn_login").html("登录中...");
        }
    });
}
//获取数据源
var getDataSourceDetails = function () {
    $.ajax({
        url: apiUrl,
        data: {
            "sys:sno": "ETL",
            "sys:act": "GetDataSource",
            "DataServiceId": serviceId,
            "DataSourceId": sourceId
        },
        dataType: "json",
        success: function (data) {
            if (data.IsSccuess) {
                var str = "";
                $("#SourceName").val(data.Data.Name);//名称
                ProductionTable(data.Data.Parameters);
                //AppadParameterData(data.Data.Parameters);//组装数据并并填充表格
            } else {
                if (IsLogined(data.ErrorCode)) {
                    alert(data.Message);
                }
            }
        },
        beforeSend: function () {
            // $("btn_login").html("登录中...");
        }
    });
}
var getServiceTypeName = function (typeId) {
    if (ServiceTypelist != null && ServiceTypelist.length != 0) {
        for (var i = 0; i < ServiceTypelist.length; i++) {
            if (typeId == ServiceTypelist[i].Id) {
                return ServiceTypelist[i].Caption;
            }
        }
    }
    return "暂无";
}


var ProductionTable = function (data) {

    var trlist = "";
    for (var i = 0; i < data.length; i++) {
        var $this = data[i];
        trlist += AssembleData({ name: $this.Name, type: $this.Type, editNum: i, Id: $this.Id });
    }
    $("#table-details").append(trlist);


}

//传入data对象返回一行的表格数据
var AssembleData = function (data) {
    var tr = ("<tr data='" + JSON.stringify(data) + "'><td>");
    tr += (data.name + "</td>");
    tr += ("<td>" + data.type + "</td>");
    tr += ("<td><select onchange='changedtcoltype(this)' id=\"dtcol-type-" + data.editNum + "\"  >");
    tr += "<option value=\"1\">具体值</option>";
    tr += "<option value=\"2\">表达式</option>";
    tr += "<option value=\"3\">循环数组</option>";
    tr += ("</select></td>");
    tr += ("<td  style=\"padding: 4px 2px;\"><input type=\"text\" value=\"\" style=\"width:80%;height:22px !important;\" name='dtcol-value-" + data.editNum + "'  id=\"dtcol-value-" + data.editNum + "\"  /><i onclick='showvaluetip()' class=\" fa fa-question-circle type2\" style='display:none;margin-left:5px;cursor: pointer;font-size:15px;'></i><i onclick='showvaluetip3()' class=\" fa fa-question-circle type3\" style='display:none;margin-left:5px;cursor: pointer;font-size:15px;'></i></td></tr>");
    return tr;
}
//删除当前行数据
var DeleteData = function (obj) {
    if (confirm("是否删除？")) {
        $(obj).parent().parent().remove();
    }
}
var changedtcoltype = function (obj) {
    var $this = $(obj);
    if ($this.val() == "2") {
        $this.parent().next().children().addClass("required");
        $this.parent().next().children().show();
        $this.parent().parent().find(".type3").hide();
    } else if ($this.val() == "3") {
        $this.parent().next().children().show();
        $this.parent().parent().find(".type2").hide();;
        $this.parent().next().children().first().removeClass("required");
        $this.parent().next().children().removeClass("invalid");
    } else {
        $this.parent().parent().find(".type2").hide();;
        $this.parent().parent().find(".type3").hide();;
        $this.parent().next().children().first().removeClass("required");
        $this.parent().next().children().removeClass("invalid");
    }
}
var showvaluetip = function () {
    $("#valuetip").modal("show");
}
var showvaluetip3 = function () {
    $("#valuetip3").modal("show");
}